//
//  PictureBrowserVC.m
//  CenturyCity
//
//  Created by beisheng03 on 2017/12/23.
//  Copyright © 2017年 beisheng. All rights reserved.
//

#import "PictureBrowserVC.h"

@interface PictureBrowserVC ()<UICollectionViewDataSource,UICollectionViewDelegate>
@property (nonatomic, weak) UICollectionView *collectionView;
@property (nonatomic, strong) NSIndexPath *selectIndex;
@property (nonatomic, strong) NSArray *picURLs;
@property (nonatomic, assign) BOOL hiddeState;

@end


//定义布局对象
@interface PictureBrowserLayout : UICollectionViewFlowLayout

@end

#pragma mark - 自定义图片浏览器UICollectionViewCell
@interface PictureBrowserCell : UICollectionViewCell<UIScrollViewDelegate>
@property (nonatomic, weak) NSURL *picURL;

@property (nonatomic, weak) UIImageView *imageView;

@property (nonatomic, strong)void(^dismissBlock)(void);


@end


#pragma mark - 自定义下载进度视图
@interface PictureBrowserProgressView:UIView

@property (nonatomic, assign) CGFloat currtProgress;
@end

@implementation PictureBrowserVC



- (UICollectionView *)collectionView{
    if (!_collectionView) {

        UICollectionView *coll = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, KScreenW + 20, KScreenH) collectionViewLayout:[[PictureBrowserLayout alloc]init]];
        coll.dataSource = self;
        coll.delegate = self;
        coll.backgroundColor = [UIColor blackColor];
        coll.showsVerticalScrollIndicator = false;
        coll.showsHorizontalScrollIndicator = false;
        coll.showsHorizontalScrollIndicator = NO;
        coll.pagingEnabled = YES;
        [coll registerClass:[PictureBrowserCell class] forCellWithReuseIdentifier:NSStringFromClass([PictureBrowserCell class])];
        _collectionView = coll;
        
        [self.view addSubview:_collectionView];
    }
    
    return _collectionView;
    
}


+ (instancetype)pictureBrowserControllerWith:(NSIndexPath *)index picURLs:(NSArray *)urls{
    
    PictureBrowserVC *photoVC = [[PictureBrowserVC alloc]init];
    photoVC.selectIndex = index;
    photoVC.picURLs = urls;
    
    photoVC.navigationItem.title = [NSString stringWithFormat:@"1/%d",urls.count];

    return photoVC;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.hiddeState = NO;
    
    [self setNav];
    
    
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    

    

    [self.collectionView registerClass:[PictureBrowserCell class] forCellWithReuseIdentifier:@"PictureBrowserCell"];
    

    
    if (@available(iOS 11.0, *)) {
        
        self.collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        
    }
    
    // Do any additional setup after loading the view.
}




- (void)setNav{
    
    UIButton *but = [UIButton buttonWithType:UIButtonTypeCustom];
    [but setImage:[UIImage imageNamed:@"nav_back"] forState:UIControlStateNormal];
    [but setImage:[UIImage imageNamed:@"nav_back"] forState:UIControlStateHighlighted];
    
    [but addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    
    
    but.imageView.contentMode = UIViewContentModeScaleAspectFit;
    
    //        but.backgroundColor = [UIColor redColor];
    
    but.frame = CGRectMake(0, 0, 44, 44);
    but.contentEdgeInsets = UIEdgeInsetsMake(11, -10, 11, 22);
    
    UIBarButtonItem *returnButtonItem = [[UIBarButtonItem alloc]initWithCustomView:but];
    
    
    self.navigationItem.leftBarButtonItem = returnButtonItem;
}


- (void)back{
    
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)viewDidAppear:(BOOL)animated{
    
    [super viewDidAppear:animated];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.picURLs.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    
    PictureBrowserCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PictureBrowserCell" forIndexPath:indexPath];
    
    
    cell.picURL = self.picURLs[indexPath.item];
    __weak  typeof(self)  weakSelf = self;
    
    cell.dismissBlock = ^{
        
        weakSelf.hiddeState = !weakSelf.hiddeState;
        
        [self.navigationController setNavigationBarHidden:weakSelf.hiddeState animated:YES];

        
//        [weakSelf dismissViewControllerAnimated:YES completion:nil];
        
        
    };
    
    return cell;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    NSInteger curruetPage = scrollView.contentOffset.x / (KScreenW + 20);
    
    self.navigationItem.title = [NSString stringWithFormat:@"%d/%d",curruetPage + 1,self.picURLs.count];

//    NSLog(@"--------");
    
}

#pragma mark <UICollectionViewDelegate>

/*
// Uncomment this method to specify if the specified item should be highlighted during tracking
- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
	return YES;
}
*/

/*
// Uncomment this method to specify if the specified item should be selected
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
*/

/*
// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
- (BOOL)collectionView:(UICollectionView *)collectionView shouldShowMenuForItemAtIndexPath:(NSIndexPath *)indexPath {
	return NO;
}

- (BOOL)collectionView:(UICollectionView *)collectionView canPerformAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
	return NO;
}

- (void)collectionView:(UICollectionView *)collectionView performAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
	
}
*/




@end





@implementation PictureBrowserLayout
- (void)prepareLayout{
    [super prepareLayout];

    self.itemSize  = CGSizeMake(KScreenW + 20, KScreenH + 20);
    self.minimumLineSpacing = 0;
    self.minimumInteritemSpacing = 0;

     self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
}
@end



@implementation PictureBrowserProgressView
- (void)setCurrtProgress:(CGFloat)currtProgress{
    _currtProgress = currtProgress;
    [self setNeedsDisplay];
    
}

- (void)drawRect:(CGRect)rect{
    [super drawRect:rect];
    CGPoint center = CGPointMake(rect.size.width * 0.5, rect.size.height * 0.5);
    CGFloat radius = rect.size.width * 0.5 -3;
    CGFloat starAngle = -M_PI_2;
    CGFloat endAngle = (CGFloat)(2 * M_PI) * _currtProgress + starAngle;
    
    UIBezierPath *bezipath = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:starAngle endAngle:endAngle clockwise:YES];
    
    [bezipath addLineToPoint:center];
    
    [bezipath closePath];
    
    
    [[UIColor grayColor] setFill];
    
    
    [bezipath fill];
    
}
@end




@implementation PictureBrowserCell{
    UIScrollView *_scrollView;
    
    PictureBrowserProgressView *_photoBrowserProgressView;
    
    UIButton *_dowloadBtn;
    
}

-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.contentView.backgroundColor = [UIColor blackColor];
        UIImageView *imageView = [[UIImageView alloc]init];
        _imageView = imageView;
        imageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(imageViewClick:)];
        [imageView addGestureRecognizer:tap];
        
        UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(imageViewDubClick:)];
        tap2.numberOfTapsRequired = 2;
        [imageView addGestureRecognizer:tap2];
        
        [tap requireGestureRecognizerToFail:tap2];
        UIScrollView *scroll = [[UIScrollView alloc]initWithFrame:self.contentView.bounds];
        CGRect rect = scroll.frame;
        rect.size.width -=20;
        scroll.frame = rect;
        [self.contentView addSubview:scroll];
        _scrollView = scroll;
        [scroll addSubview:imageView];
        
        scroll.delegate = self;
        scroll.minimumZoomScale = 1.0;
        scroll.maximumZoomScale = 2.0;
        
        if (@available(iOS 11.0, *)) {
            
            scroll.contentInsetAdjustmentBehavior = UIApplicationBackgroundFetchIntervalNever;
            
        }
        
        PictureBrowserProgressView *progress = [[PictureBrowserProgressView alloc]initWithFrame:CGRectMake(([UIScreen mainScreen].bounds.size.width - 50) / 2.0, ([UIScreen mainScreen].bounds.size.height - 50) / 2.0, 50, 50)];
        progress.hidden = YES;
        progress.layer.cornerRadius = 25;
        progress.layer.masksToBounds = YES;
        progress.backgroundColor = [UIColor lightGrayColor];
        _photoBrowserProgressView  = progress;
        [self.contentView addSubview:progress];
        
        UIButton *dowBtn = [UIButton buttonWithType:UIButtonTypeCustom];//
        
        CGFloat dowbtnH = IPhoneX ? KScreenH - 72 : KScreenH - 40;
        
        dowBtn.frame = CGRectMake(KScreenW - 50, dowbtnH, 40, 40);
        
        dowBtn.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);

        
        [dowBtn addTarget:self action:@selector(saveImage) forControlEvents:UIControlEventTouchUpInside];
        
        dowBtn.hidden = YES;
        
        _dowloadBtn = dowBtn;
        
        [dowBtn setImage:[UIImage imageNamed:@"rentHousedownload1"] forState:UIControlStateNormal];
        [dowBtn setImage:[UIImage imageNamed:@"rentHousedownload1"] forState:UIControlStateHighlighted];

        [self.contentView addSubview:dowBtn];
        
        
        
        
    }
    
    
    return self;
}


- (void)saveImage{
    
    
    UIImageWriteToSavedPhotosAlbum(_imageView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    NSString *message;
    if (error == nil) {
        message = @"保存成功";
        [SVProgressHUD showSuccessWithStatus:message];
        
    }else{
        message = @"保存失败";
        [SVProgressHUD showErrorWithStatus:message];
    }
    
    
}


- (void)setPicURL:(NSURL *)picURL{
    _picURL = picURL;
    
    UIImage *image0 = [[[SDWebImageManager sharedManager] imageCache] imageFromDiskCacheForKey:_picURL.absoluteString];
    
    CGFloat screenH = [UIScreen mainScreen].bounds.size.height;
    CGFloat screenW = [UIScreen mainScreen].bounds.size.width;
    _dowloadBtn.hidden = YES;
    if (image0) {
        _dowloadBtn.hidden = NO;

        _imageView.image = image0;
        
        CGFloat imageViewH = screenW / image0.size.width * image0.size.height;
        // 重置放大缩小的比例
        _scrollView.zoomScale = 1.0;
        _imageView.frame = CGRectMake(0, 0, screenW, imageViewH);
        _scrollView.contentSize = _imageView.frame.size;
        
        // 5.设置内边距,确定imageView的位置
        CGFloat topInset = 0;
        if (imageViewH < screenH) { // 短图
            topInset = (screenH - imageViewH) * 0.5;
        } else { // 长图
            topInset = 0;
            _scrollView.contentOffset = CGPointZero;
        }
        _scrollView.contentInset = UIEdgeInsetsMake(topInset, 0, 0, 0);
        
        _photoBrowserProgressView.hidden = YES;

        
    } else {
        
        _photoBrowserProgressView.hidden = NO;
        
        [[SDWebImageManager sharedManager] downloadImageWithURL:_picURL options:kNilOptions progress:^(NSInteger receivedSize, NSInteger expectedSize) {
            
            _photoBrowserProgressView.currtProgress = (CGFloat)receivedSize/expectedSize;
            
        } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
            
            if (image) {
                _imageView.image = image;
                _dowloadBtn.hidden = NO;

                CGFloat imageViewH = screenW / image.size.width * image.size.height;
                // 重置放大缩小的比例
                _scrollView.zoomScale = 1.0;
                _imageView.frame = CGRectMake(0, 0, screenW, imageViewH);
                _scrollView.contentSize = _imageView.frame.size;
                
                // 5.设置内边距,确定imageView的位置
                CGFloat topInset = 0;
                if (imageViewH < screenH) { // 短图
                    topInset = (screenH - imageViewH) * 0.5;
                } else { // 长图
                    topInset = 0;
                    _scrollView.contentOffset = CGPointZero;
                }
                _scrollView.contentInset = UIEdgeInsetsMake(topInset, 0, 0, 0);
                
                _photoBrowserProgressView.hidden = YES;
            } 
            
         
        }];
    }
    

}


- (void)imageViewClick:(UIGestureRecognizer *)gest{
    if (self.dismissBlock) {
        self.dismissBlock();
    }
    
    
}

- (void)imageViewDubClick:(UIGestureRecognizer *)gest{
    
    if ( _scrollView.zoomScale == 1) {
        
        
        [UIView animateWithDuration:0.5 animations:^{
            
            _scrollView.zoomScale = 2.0;
            
            
        }];
        
        [self scrollViewDidEndZooming:_scrollView withView:_imageView atScale:2.0];
        
      
    } else {
        
        
        
        [UIView animateWithDuration:0.5 animations:^{
            
            _scrollView.zoomScale = 1;
            
            
        }];
        
        
        CGFloat imageH = _imageView.frame.size.height;
        CGFloat imageW = _imageView.frame.size.width;
        
        CGFloat screenH = [UIScreen mainScreen].bounds.size.height;
        CGFloat screenW = [UIScreen mainScreen].bounds.size.width;
        
        CGFloat topInset = imageH < screenH ? (screenH - imageH) * 0.5 : 0;
        CGFloat leftInset = imageW < screenW ? (screenW - imageW) * 0.5 : 0;
        
        [UIView animateWithDuration:0.5 animations:^{
            
            _scrollView.contentInset = UIEdgeInsetsMake(topInset, leftInset, topInset, leftInset);
            
            
        }];
        
       
    }

    
    
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    
    return _imageView;
}

- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale{
    
    CGFloat imageH = view.frame.size.height;
    CGFloat imageW = view.frame.size.width;
    
    CGFloat screenH = [UIScreen mainScreen].bounds.size.height;
    CGFloat screenW = [UIScreen mainScreen].bounds.size.width;
    
    CGFloat topInset = imageH < screenH ? (screenH - imageH) * 0.5 : 0;
    CGFloat leftInset = imageW < screenW ? (screenW - imageW) * 0.5 : 0;
    
    scrollView.contentInset = UIEdgeInsetsMake(topInset, leftInset, topInset, leftInset);
    
    
    
}


@end
